import fs from 'fs';
import highlight from 'highlight.js';
import lodash from 'lodash';
import { createRequire } from 'module';
import path, { dirname } from 'path';
import prettier from 'prettier';
import { fileURLToPath } from 'url';
import getCaseName from './utils/case-name/index.js';
import frontMatter from './utils/front-matter/index.js';
import { marked } from './utils/marked/index.js';
import { parse as YAMLparse } from './utils/yaml/index.js';

// 还没写完
marked.use({
  async: true,
  pedantic: false,
  gfm: true,
});

function copy(params) {
  exec('pbcopy').stdin.end(params);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const cwd = process.cwd();
const prettierrc = JSON.parse(
  fs.readFileSync(path.resolve(cwd, '.prettierrc'), 'utf8'),
);

let fp = path.resolve(cwd, 'components/mobile/_basic');
let tp = path.resolve(cwd, 'src/mobile/views');
let a = fs.readdirSync(fp, {
  // recursive: true
});
let test = true;
test = false;

if (test) {
  a = [a[13]];
}

let r = '';
for (let i = 0; i < a.length; i++) {
  const e = a[i];
  if (e.includes('.DS_Store')) {
    continue;
  }
  // if (!e.includes('cascader')) {
  //   continue;
  // }
  let f = path.resolve(fp, e);
  if (fs.existsSync(f) && fs.statSync(f).isDirectory()) {
    let README = path.resolve(f, 'README.zh-CN.md');
    let indexVuePath = path.resolve(tp, e, 'index.vue');
    let docVuePath = path.resolve(tp, e, 'Doc.vue');
    if (fs.existsSync(README) && fs.existsSync(indexVuePath)) {
      r = fs.readFileSync(README, 'utf8');
      let { attributes, body, bodyBegin, frontmatter } = frontMatter(r);
      const tokens = marked.lexer(body);
      let table = { columns: [], datas: [] };
      r =
        `<!-- 此文档由潘启宝写的脚本文件自动生成 2023年12月26日 星期二 11时27分08秒 CST 山东济南 -->
        <template><div class="doc">` +
        (await paraseMD(tokens, {
          name: e,
          table,
        })) +
        `</div></template>
        `;

      r += ` <script setup lang="js">
  `;
      table.columns.forEach((v, i) => {
        r += `let tableColumn${i + 1} =` + v + ';';
      });
      table.datas.forEach((v, i) => {
        r += `let tableData${i + 1} =` + v + ';';
      });
      r += `
</script>`;
      r += `
        <style lang="less">
  .doc {
  }
</style>`;

      r = await prettier.format(r, { parser: 'vue' });
      fs.writeFileSync(docVuePath, r, {
        encoding: 'utf-8',
      });

      r = fs.readFileSync(indexVuePath, 'utf8');
      if (!r.includes('import Doc')) {
        r =
          `<!-- 此 demo 由潘启宝写的脚本文件自动生成 2023年12月26日 星期二 11时30分18秒 CST 山东济南 -->` +
          r;
        let i = r.indexOf('<script');
        i = r.indexOf('>', i) + 1;
        r = r.substring(0, i) + `import Doc from './Doc.vue';` + r.substring(i);
      } else {
      }

      if (!r.includes('<Doc')) {
        let i = r.lastIndexOf('/template>') - 1;
        r = r.substring(0, i) + '<Doc />' + r.substring(i);
      }

      r = await prettier.format(r, { parser: 'vue' });
      fs.writeFileSync(indexVuePath, r, {
        encoding: 'utf-8',
      });
    } else {
      // console.log(e);
    }
  }
}

async function paraseMD(tokens, other) {
  let { name, demoName, text, table } = other ?? {};
  const { ComponentsCaseName: demoComponentsCaseName } = getCaseName(demoName);
  let elementString = '';
  for (let i = 0; i < tokens?.length; i++) {
    const e = tokens[i];
    let {
      type,
      raw,
      depth,
      lang,
      text: text_,
      tokens: tokens_,
      loose,
      start,
      items,
      ordered,
      href,
      header,
      align,
      rows,
    } = e ?? {};
    // console.log(e);
    let t = (await paraseMD(tokens_ ?? items, { ...other, text: text_ })) ?? '';

    switch (type) {
      case 'code': {
        let l = 'html';

        switch (lang) {
          case 'yaml': {
            let { title } = YAMLparse(text_) || {};
            // let a = Object.entries(title)
            //   .sort((a, b) => {
            //     return a[0] > b[0] ? 1 : -1;
            //   })
            //   .reverse()
            //   .map(v => v[1]);
            // elementString += `<h2 class={['title']}>${a.join(' ')}</h2>`;
            break;
          }
          case 'html': {
            break;
          }
          case 'javascript':
          case 'js': {
            l = 'javascript';
            break;
          }
          case 'ts': {
            l = 'typescript';
            break;
          }
          case 'less': {
            l = 'css';
            break;
          }
          case 'css': {
            l = 'css';
            break;
          }
          case 'bash': {
            break;
          }
          case 'vue': {
            break;
          }

          default: {
            console.error('出现新语言：', lang);
            break;
          }
        }
        t &&= false
          ? lodash.escape(t).trim()
          : highlight.highlight(t, { language: l }).value;

        if (lang === 'html') {
          let r = /{{(.*?)}}/g;
          if (r.test(t)) {
            t = t.replace(r, `<span v-pre>{{ $1 }}</span>`);
          }
        }

        elementString += `<tp-alert type="normal"><pre class="doc-pre"><code class="doc-code">${t}</code></pre></tp-alert>`;
        break;
      }
      case 'space': {
        elementString += `<br class="doc-br"/>`;
        break;
      }
      case 'heading': {
        elementString += `<h${depth} class="doc-h">${t}</h${depth}>`;
        break;
      }
      case 'paragraph': {
        elementString += `<p class="doc-p">${t}</p>`;
        break;
      }
      case 'hr': {
        elementString += `<hr class="doc-hr"/>`;
        break;
      }
      case 'text': {
        elementString += `<span class="doc-text">${t}</span>`;
        break;
      }
      case 'codespan': {
        elementString += `<span class="doc-codespan">${t}</span>`;
        break;
      }
      case 'strong': {
        elementString += `<b class="doc-strong">${t}</b>`;
        break;
      }
      case 'em': {
        elementString += `<em class="doc-em">${t}</em>`;
        break;
      }
      case 'link': {
        elementString += `<a class="doc-link">${t}</a>`;
        break;
      }
      case 'table': {
        table.columns ||= [];
        table.datas ||= [];
        table.columns.push(
          JSON.stringify(
            header
              .filter(v => v.text !== '版本')
              .map((v, i) => {
                let o = {
                  title: v.text,
                  dataIndex: v.text,
                };
                return o;
              }),
          ),
        );
        table.datas.push(
          JSON.stringify(
            rows.map((v, i) => {
              let o = { key: i + '' };
              v.forEach(async (v_, i_) => {
                let text = header[i_].text;
                if (text !== '版本') {
                  // o[text] =
                  //   (await paraseMD(v_?.tokens, { ...other, text: v_.text })) ??
                  //   '';
                  if (v_?.tokens?.length) {
                    o[text] = v_.text.replace(/^_/, '').replace(/_$/, '');
                  } else {
                    o[text] = v_.text;
                  }
                }
              });
              return o;
            }),
          ),
        );
        elementString += `<tp-table
        :columns="tableColumn${table.columns.length}"
        :data='tableData${table.datas.length}'
      :pagination='false'
      />`;
        break;
      }
      case 'list': {
        elementString += `<ul class="doc-ul">${t}</ul>`;
        break;
      }
      case 'list_item': {
        elementString += `<li class="doc-li">${t}</li>`;
        break;
      }
      case 'blockquote': {
        elementString += `<tp-alert class="doc-blockquote">${t}</tp-alert>`;
        break;
      }
      case 'escape': {
        elementString += t;
        break;
      }

      default: {
        console.error('出现新类型：', type);
        break;
      }
    }
  }

  return elementString || text;
}
